package com.inossem.warehousestorage_inossem.activity.inventory;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.UtilsConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.bean.common.KeyValueBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryAreaBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryBatchBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryNewMatQueryReqBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryNewMatQueryRespBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryNewMatReqBean;
import com.inossem.warehousestorage_inossem.bean.inventory.InventoryRespBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.inventory.InventoryManageRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InventoryUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.ArrayList;
import java.util.List;

public class InventoryItemAddActivity extends BaseActivity {
    public static final int SELECT_MATERIEL = 100;
    public static final int SELECT_POSITION = 200;
    public static final int SELECT_SPECIAL_INVENTORY_FLAG = 300;
    public static final int SELECT_SPECIAL_INVENTORY_CODE = 400;
    public static final int SELECT_SUPPLIER_CODE = 500;

    private static final String TYPE_EDITTEXT = "0";

    private static final String TYPE_DATEPICKER = "1";

    private static final String TYPE_SELECT = "2";


    private static final String REQUIRED_YES = "1";

    private TextView title,materielCode,specialInventoryFlag,specialInventoryFlagSep,specialInventoryFlagValue,materielDescription
            ,specialInventoryDescription,inStorageDate,supplierDescription
            ,save,del,positionNumber
            ,specialInventoryCode
            ,supplierCode
            ;

    private EditText
            number
            ;

    private InventoryNewMatReqBean inventoryNewMatReqBean;

    private String areaNumberValue,positionNumberStr,warehouseNumberStr,batchStr,idStr;
    private InventoryAreaBean.DataBean areaBean;
    private InventoryNewMatQueryRespBean.DataBean.NewMaterielBean newMateriel;
    private List<InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean> batchList = new ArrayList<InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean>();
    private PercentLinearLayout batchLayout;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_inventory_item_edit);
        initView(InventoryItemAddActivity.this);
        initData(InventoryItemAddActivity.this);
    }


    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        save = (TextView) activity.findViewById(R.id.save);
        del = (TextView) activity.findViewById(R.id.del);
        this.specialInventoryDescription = (TextView) activity.findViewById(R.id.specialInventoryDescription);
        this.supplierCode = (TextView) activity.findViewById(R.id.supplierCode);
        this.number = (EditText) activity.findViewById(R.id.number);
        this.specialInventoryFlag = (TextView) activity.findViewById(R.id.specialInventoryFlag);
        this.specialInventoryFlagValue = (TextView) activity.findViewById(R.id.specialInventoryFlagValue);
        this.specialInventoryFlagSep = (TextView) activity.findViewById(R.id.specialInventoryFlagSep);

        this.materielCode = (TextView) activity.findViewById(R.id.materielCode);
        this.specialInventoryCode = (TextView) activity.findViewById(R.id.specialInventoryCode);
        this.materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        this.positionNumber = (TextView) activity.findViewById(R.id.positionNumber);

        this.inStorageDate = (TextView) activity.findViewById(R.id.inStorageDate);
        this.supplierDescription = (TextView) activity.findViewById(R.id.supplierDescription);
        this.batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);

    }

    private void initData(Activity activity) {
        title.setText(activity.getResources().getString(R.string.activity_inventory_item_title));

        ActivityUtils.initBackAndFunction(activity, activity.getResources().getString(R.string.activity_inventory_overview_title), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {


                goBack();
            }
        });

        materielCode.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, InventorySelectMaterielActivity.class);
                startActivityForResult(intent, SELECT_MATERIEL);
            }
        });
        supplierCode.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, InventorySelectSupplierActivity.class);
                startActivityForResult(intent, SELECT_SUPPLIER_CODE);
            }
        });



        positionNumber.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, InventorySelectPositionActivity.class);
                startActivityForResult(intent, SELECT_POSITION);
            }
        });

        specialInventoryFlag.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, InventorySelectSpecialInvFlagActivity.class);
                startActivityForResult(intent, SELECT_SPECIAL_INVENTORY_FLAG);
            }
        });
        specialInventoryFlagValue.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, InventorySelectSpecialInvFlagActivity.class);
                startActivityForResult(intent, SELECT_SPECIAL_INVENTORY_FLAG);
            }
        });
        this.specialInventoryCode.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                //检查是否选择了特殊库存标识
                if(TextUtils.isEmpty(specialInventoryFlag.getText().toString())){
                    Utils.middleToast(activity,"请先选择特殊库存标识");
                    return;
                }

                Intent intent = new Intent(activity, InventorySelectSpecialInvCodeActivity.class);
                intent.putExtra(InventoryExtra.SPECIAL_INVENTORY_FLAG,specialInventoryFlag.getText().toString());
                startActivityForResult(intent, SELECT_SPECIAL_INVENTORY_CODE);
            }
        });

        save.setOnClickListener( new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                genNewMatReqBean();
                if(inventoryNewMatReqBean!=null){
                    InventoryManageRequest.saveNewItem(InventoryItemAddActivity.this, inventoryNewMatReqBean, new GsonBeanListener<InventoryRespBean>() {
                        @Override
                        public void onSuccess(InventoryRespBean bean) {
                            if(bean.getData().getCode().equals("1")){
                                finish();
                            }else{
                                Utils.middleToast(InventoryItemAddActivity.this,bean.getData().getMsg());
                            }

                        }
                    });
                }


            }
        });
        del.setOnClickListener( new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {

                    if(newMateriel!=null){
                        InventoryManageRequest.delNewMateriel(InventoryItemAddActivity.this, newMateriel.getId(), areaBean.getFactoryCode(), new GsonBeanListener<InventoryRespBean>() {
                            @Override
                            public void onSuccess(InventoryRespBean bean) {
                                goBack();
                            }
                        });
                    }


            }
        });
        initDateUtil(inStorageDate,"inStorageDate");


        getData(activity);

    }

    private void genNewMatReqBean() {
        inventoryNewMatReqBean = new InventoryNewMatReqBean();
        if(newMateriel!=null){
            inventoryNewMatReqBean.setId(newMateriel.getId());
        }

        inventoryNewMatReqBean.setInventoryVoucher(areaBean.getInventoryVoucher());
        inventoryNewMatReqBean.setAreaNumberValue(areaNumberValue);
        inventoryNewMatReqBean.setWarehouseNumber(warehouseNumberStr);
        inventoryNewMatReqBean.setBatch(batchStr);
        inventoryNewMatReqBean.setMaterielCode(materielCode.getText().toString());
        //物料编码必填
        if(TextUtils.isEmpty(inventoryNewMatReqBean.getMaterielCode())){
            Utils.middleToast(InventoryItemAddActivity.this,"物料编号是必填的");
            inventoryNewMatReqBean=null;
            return;
        }

        inventoryNewMatReqBean.setMaterielDescription(materielDescription.getText().toString());

        inventoryNewMatReqBean.setPositionNumberValue(positionNumber.getText().toString());

        if(TextUtils.isEmpty(inventoryNewMatReqBean.getPositionNumberValue())){
            Utils.middleToast(InventoryItemAddActivity.this,"仓位编号是必填的");
            inventoryNewMatReqBean=null;
            return;
        }


        inventoryNewMatReqBean.setNumber(number.getText().toString());

        if(TextUtils.isEmpty(inventoryNewMatReqBean.getNumber())){
            Utils.middleToast(InventoryItemAddActivity.this,"实盘数量是必填的");
            inventoryNewMatReqBean=null;
            return;
        }
        if(!RegexUtils.checkDecimal(inventoryNewMatReqBean.getNumber())){
            Utils.middleToast(InventoryItemAddActivity.this,"调整数量不合法");
            number.requestFocus();
            inventoryNewMatReqBean=null;
            return;
        }


        inventoryNewMatReqBean.setSpecialInventoryFlag(specialInventoryFlag.getText().toString());


        inventoryNewMatReqBean.setSpecialInventoryCode(specialInventoryCode.getText().toString());


        inventoryNewMatReqBean.setSpecialInventoryDescription(specialInventoryDescription.getText().toString());




        inventoryNewMatReqBean.setSupplierCode(supplierCode.getText().toString());


        inventoryNewMatReqBean.setInStorageDate(inStorageDate.getText().toString());




        inventoryNewMatReqBean.setSupplierDescription(supplierDescription.getText().toString());

        for (int i = 0; i < batchList.size(); i++) {
            InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean batchItem =  batchList.get(i);
            InventoryNewMatReqBean.BatchListBean ble = new InventoryNewMatReqBean.BatchListBean();
            String type = batchItem.getType();
            View view = findViewById(i + 1);
            ble.setId(batchItem.getId());
            ble.setType(type);
            switch (type) {
                case TYPE_EDITTEXT:
                    ble.setText(((EditText) view.findViewById(R.id.text)).getText().toString());
                    //检查必填项
                    if(batchItem.getRequired().equals(REQUIRED_YES)&&TextUtils.isEmpty(ble.getText())){
                        Utils.middleToast(InventoryItemAddActivity.this,"存在必填项没有填写");
                        inventoryNewMatReqBean=null;
                        return;
                    }
                    break;

                case TYPE_DATEPICKER:
                    ble.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    //检查必填项
                    if(batchItem.getRequired().equals(REQUIRED_YES)&&TextUtils.isEmpty(ble.getText())){
                        Utils.middleToast(InventoryItemAddActivity.this,"存在必填项没有填写");
                        inventoryNewMatReqBean=null;
                        return;
                    }
                    break;
                case TYPE_SELECT:
                    ble.setValue(((TextView) view.findViewById(R.id.value)).getText().toString());
                    ble.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    //检查必填项
                    if(batchItem.getRequired().equals(REQUIRED_YES)&&TextUtils.isEmpty(ble.getValue())){
                        Utils.middleToast(InventoryItemAddActivity.this,"存在必填项没有填写");
                        inventoryNewMatReqBean=null;
                        return;
                    }
                    break;
            }
            inventoryNewMatReqBean.getNewMaterialBatchList().add(ble);
        }


    }

    private void loadBatch() {
        batchLayout.removeAllViews();
        if(batchList.size()<=0){
            return;
        }
        for (int i = 0; i < batchList.size(); i++) {
            InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean batchItem = batchList.get(i);
            String type = batchItem.getType();
            boolean required = REQUIRED_YES.equals(batchItem.getRequired()) ? true : false;
            switch (type) {
                case TYPE_EDITTEXT:
                    InventoryUtils.createEditText(this, batchLayout, batchItem.getName(), required,batchItem.getText(), i + 1);
                    break;
                case TYPE_DATEPICKER:
                    InventoryUtils.createDatePicker(InventoryItemAddActivity.this, batchLayout, batchItem.getName(), required,batchItem.getText(), i + 1);
                    break;
                case TYPE_SELECT:
                    List<KeyValueBean.ListBean> list = new ArrayList<KeyValueBean.ListBean>();
                    for (InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean.SelectBean sb : batchItem.getSelect() ) {
                        KeyValueBean.ListBean l = new KeyValueBean.ListBean();
                        l.setCode(sb.getValue());
                        l.setValue(sb.getText());
                        list.add(l);
                    }
                    InventoryUtils.createSelect(this, batchLayout, batchItem.getName(), required, batchItem.getValue(), list, i + 1);
                    break;
            }
        }
    }

    private void initDateUtil(TextView inStorageDate, String tag) {
        inStorageDate.setText(Utils.getCurrentStringDate(UtilsConstant.YYYY_MM_DD));
        inStorageDate.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if(TextUtils.isEmpty(inStorageDate.getText().toString())){
                    inStorageDate.setText(Utils.getCurrentStringDate(UtilsConstant.YYYY_MM_DD));
                }
                ActivityUtils.getTimePickerDialog(InventoryItemAddActivity.this, InventoryItemAddActivity.this.getResources().getString(R.string.activity_receive_receive_item_receive_date), inStorageDate.getText().toString(), new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        inStorageDate.setText(Utils.getStringDateFromTimeStamp(UtilsConstant.YYYY_MM_DD, millseconds));
                        inStorageDate.setTextColor(ContextCompat.getColor(InventoryItemAddActivity.this, R.color.common_font_content));
                    }
                }).show(getSupportFragmentManager(), tag);
            }
        });

    }


    private void goBack() {
        DialogUtils.getConfirmDialog(this, "退出将不保存所有信息", new DialogUtils.ConfirmDialogListener() {
            @Override
            public void onConfirm(Dialog dialog) {
                finish();
            }
        }).show();

    }

    private void getData(Activity activity) {
        areaNumberValue = activity.getIntent().getStringExtra(InventoryExtra.AREA_NUMBER_VALUE);
        positionNumberStr = activity.getIntent().getStringExtra(InventoryExtra.POSITION_NUMBER_VALUE);
        idStr = activity.getIntent().getStringExtra(InventoryExtra.ID);
        areaBean = SPUtils.getInformation(activity,InventoryAreaBean.DataBean.class,SPUtils.KEY_INVENTORY_INFORMATION);
        if(!TextUtils.isEmpty(positionNumberStr)&&!TextUtils.isEmpty(areaNumberValue)){
            InventoryNewMatQueryReqBean query = new InventoryNewMatQueryReqBean();
            query.setFactoryCode(areaBean.getFactoryCode());
            query.setId(idStr);
            InventoryManageRequest.getNewMateriel(InventoryItemAddActivity.this, query, new GsonBeanListener<InventoryNewMatQueryRespBean>() {
                @Override
                public void onSuccess(InventoryNewMatQueryRespBean bean) {

                    load(bean);
                }
            });
        }

    }

    private void load(InventoryNewMatQueryRespBean bean) {
        newMateriel = bean.getData().getNewMateriel();
        materielCode.setText(newMateriel.getMaterielCode());
        warehouseNumberStr = newMateriel.getWarehouseNumber();
        batchStr = newMateriel.getBatch();
        materielDescription.setText(newMateriel.getMaterielDescription());

        positionNumber.setText(newMateriel.getPositionNumberValue());

        number.setText(newMateriel.getNumber());

        specialInventoryFlag.setText(newMateriel.getSpecialInventoryFlagCode());
        specialInventoryFlagValue.setText(newMateriel.getSpecialInventoryFlagValue());
        if(!TextUtils.isEmpty(newMateriel.getSpecialInventoryFlagValue())){
            specialInventoryFlagSep.setVisibility(View.VISIBLE);
        }

        specialInventoryCode.setText(newMateriel.getSpecialInventoryCode());

        specialInventoryDescription.setText(newMateriel.getSpecialInventoryDescription());


        supplierCode.setText(newMateriel.getSupplierCode());
        supplierDescription.setText(newMateriel.getSupplierDescription());

        inStorageDate.setText(newMateriel.getInStorageDate());


        this.batchList = newMateriel.getBatchList();

        loadBatch();
    }


    @Override
    public void onBackPressed() {
        goBack();
    }


    @Override
    protected void onActivityResultImpl(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case SELECT_MATERIEL:
                    materielCode.setText(data.getStringExtra(InventoryExtra.MATERIEL_CODE));
                    materielDescription.setText(data.getStringExtra(InventoryExtra.MATERIEL_DESCRIPTION));
                    warehouseNumberStr = data.getStringExtra(InventoryExtra.WAREHOUSE_NUMBER);
                    findBatch();
                    break;
                case SELECT_POSITION:
                    positionNumber.setText(data.getStringExtra(InventoryExtra.CODE));
                    break;
                case SELECT_SPECIAL_INVENTORY_FLAG:
                    if(!data.getStringExtra(InventoryExtra.CODE).equals(specialInventoryFlag.getText().toString())){
                        specialInventoryFlag.setText(data.getStringExtra(InventoryExtra.CODE));
                        specialInventoryFlagValue.setText(data.getStringExtra(InventoryExtra.DESCRIPTION));
                        specialInventoryFlagSep.setVisibility(View.VISIBLE);
                        //选择特殊库存标识后，需要清空特殊库存代码和描述
                        specialInventoryCode.setText("");
                        specialInventoryDescription.setText("");
                    }

                    break;
                case SELECT_SPECIAL_INVENTORY_CODE:
                    specialInventoryCode.setText(data.getStringExtra(InventoryExtra.CODE));
                    specialInventoryDescription.setText(data.getStringExtra(InventoryExtra.DESCRIPTION));
                    break;
                case SELECT_SUPPLIER_CODE:
                    supplierCode.setText(data.getStringExtra(InventoryExtra.CODE));
                    supplierDescription.setText(data.getStringExtra(InventoryExtra.DESCRIPTION));
                    break;
            }
        }
    }

    private void findBatch() {
        InventoryManageRequest.findBatch(this,materielCode.getText().toString(),areaBean.getFactoryCode(),new GsonBeanListener<InventoryBatchBean>(){
            @Override
            public void onSuccess(InventoryBatchBean bean) {
                List<InventoryBatchBean.DataBean.BatchBean> bl = bean.getData().getBatch();
                batchList =  new ArrayList<InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean>();
                if(bl!=null&&bl.size()>0){
                    for (InventoryBatchBean.DataBean.BatchBean bb :bl){
                        InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean bdb = new InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean();
                        bdb.setId(bb.getId());
                        bdb.setType(bb.getType());
                        bdb.setName(bb.getName());
                        bdb.setRequired(bb.getRequired());
                        List<InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean.SelectBean> seles = new ArrayList<InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean.SelectBean>();
                        List<InventoryBatchBean.DataBean.BatchBean.SelectBean> bbs = bb.getSelect();
                        if(bbs!=null&&bbs.size()>0){
                            for (InventoryBatchBean.DataBean.BatchBean.SelectBean bbi:bbs){
                                InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean.SelectBean selesItem = new InventoryNewMatQueryRespBean.DataBean.NewMaterielBean.BatchListBean.SelectBean();
                                selesItem.setValue(bbi.getValue());
                                selesItem.setText(bbi.getText());
                                seles.add(selesItem);
                            }

                        }
                        bdb.setSelect(seles);
                        batchList.add(bdb);
                    }
                }
                loadBatch();
            }
        });
    }
}
